<?php
class Form_validator
{
	private $__Rules = array();
	public $Errors = array();

	public function __construct()
	{
		
	}

	public function Add_rule($field, $type, $message)
	{
		$this->__Rules[$field][] = array($type, $message, $field);
	}

	public function Validate()
	{
		$this->data = $this->Sanitize($_POST);

		foreach($this->__Rules as $field => $rules)
		{
			$value = trim($this->data[$field]);

			foreach($rules as $rule)
			{
				$error = false;

				if(!in_array($field, $this->Errors))
				{
					switch($rule[0])
					{
						case 'int':
							if(!is_int($value)) $error = true;
							break;
						case 'number':
							if(!is_numeric($value)) $error = true;
							break;
						case 'email':
							if(!filter_var($value, FILTER_VALIDATE_EMAIL)) $error = true;
							break;
						case 'date':
							if(!preg_match('/(0[1-9]|[12][0-9]|3[01])[\/](0[1-9]|1[012])[\/](19|20)[0-9]{2}/', $value)) $error = true;
							break;
						case 'required':
						default:
							if(strlen($value) < 1) $error = true;
							break;
					}

					if($error) 
					{
						array_push($this->Errors, array("message" => $rule[1], "field" => $rule[2]));
					}
				}
			}
		}
	}

	public function Is_errors()
	{
		return count($this->Errors) > 0 ? true : false;
	}

	public function Print_errors()
	{
		$str .= '<div class="error">';

		if(is_array($this->Errors)) {
			if(count($this->Errors) > 0)
			{
				$str .= '<ul>';
				foreach($this->Errors as $err)
				{
					$str .= '<li>' . $err . '</li>' . "\n";
				}
				$str .= '</ul>';
			}
		}
		$str .= '</div>';
		return $str;
	}

	public function Print_errors_as_array()
	{
		$temp_array = array();
		
		if(is_array($this->Errors)) {
			if(count($this->Errors) > 0)
			{
				foreach($this->Errors as $err)
				{
					$temp_array[] = $err;
				}
			}
		}
		return $temp_array;
	}

	function Sanitize($data) {
		$cleaned = array();

		foreach($data as $key => $value) {
			$cleaned[$key] = empty($value) || is_null($value) ? null : trim($value);
		}
		return $cleaned;
	}
}
?>